package com.laikan.reader.article.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.article.adapter.ArticleSearchAdapter;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.ArticleSearchBean;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.MultipleTextView;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SnackBarNotice;
import com.laikan.reader.core.view.TipInfoLayout;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/11/8.
 */
public class ArticleSearchActivity extends BasicActivity implements View.OnClickListener, TextWatcher {

    private AutoCompleteTextView auto_tv_search;

    private ImageView iv_back, iv_clear_searchtext;
    private ListView search_listview;
    private ArticleSearchAdapter ArticleSearchListAdapter;
    private String searchKeyword;
    private RelativeLayout rl_search_btn;
    private ArrayList<ArticleSearchBean.BookFocusDataList> mArticleBeanList;
    private LinearLayout ll_search_history;
    private MultipleTextView multiple_tv_search_record;
    private ImageView iv_clear_searchrecord;
    private ScrollView search_scroll;
    private String[] mArticleSearchHistory;
    private boolean mIsArticleSearchList = false;
    Drawable drawable_back_tv;
    private int mCurrentPage = 1;
    private ProgressBar_Modern mModernLoadProgressBar;
    private RelativeLayout back_layout;
    private boolean mIsSearchRequestFinish = true;
    private TipInfoLayout tipinfo;
    private View search_foot_view;
    private ArticleSearchBean data;
    public MultipleTextView.OnMultipleTVItemClickListener onMultClient = new MultipleTextView.OnMultipleTVItemClickListener() {

        @Override
        public void onMultipleTVItemClick(View view, int position) {
            if (mIsSearchRequestFinish) {
                mIsSearchRequestFinish = false;
                auto_tv_search.setText(mArticleSearchHistory[position]);
                searchKeyword = mArticleSearchHistory[position];
                auto_tv_search.setSelection(auto_tv_search.getText().length()); //将光标移动到最后
                searchArticleData();
            }
        }
    };

    public void searchArticleData() {
        auto_tv_search.clearFocus();
        searchKeyword = auto_tv_search.getText().toString();
        if (TextUtils.isEmpty(searchKeyword.trim())) {
            ToastMgr.showShortToast(R.string.search_enter_empty);
            mIsSearchRequestFinish = true;
        }else {
            resetData();
            hideSoftkeyBoard(auto_tv_search);
            saveHistory(auto_tv_search);
            getSearchData(true);
        }
        refreshSearchHistory();
    }

    @Override
    protected void onPause() {
        super.onPause();
        auto_tv_search.clearFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void assignViews() {
        search_foot_view = View.inflate(mContext, R.layout.search_new_foot_view, null);
        setContentView(R.layout.activity_article_search);
        search_scroll = (ScrollView)findViewById(R.id.search_scroll);
        mArticleBeanList = new ArrayList<>();
        iv_back = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        auto_tv_search = (AutoCompleteTextView)findViewById(R.id.auto_tv_search);
        auto_tv_search.setCursorVisible(false);
        rl_search_btn = (RelativeLayout)findViewById(R.id.rl_search_btn);
        iv_clear_searchrecord = (ImageView)findViewById(R.id.iv_clear_searchrecord);
        iv_clear_searchtext = (ImageView)findViewById(R.id.iv_clear_searchtext);
        ll_search_history = (LinearLayout)findViewById(R.id.ll_search_history);
        multiple_tv_search_record = (MultipleTextView)findViewById(R.id.multiple_tv_search_record);
        mModernLoadProgressBar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        tipinfo = (TipInfoLayout)findViewById(R.id.tip_info);
        WindowManager wm = this.getWindowManager();
        ArticleSearchListAdapter = new ArticleSearchAdapter(mContext, mArticleBeanList);
        search_listview = (ListView)findViewById(R.id.search_listview);
        search_listview.addFooterView(search_foot_view);
        search_listview.setOverScrollMode(View.OVER_SCROLL_NEVER);
        search_listview.setAdapter(ArticleSearchListAdapter);
    }

    @Override
    protected void initData() {
        search_foot_view.setVisibility(View.GONE);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);
        //        if (SPUtil.getBoolean("isKeywordSearch", true) && getIntent() != null) {
        //            mIsSearchRequestFinish = false;
        //            auto_tv_search.setText(getIntent().getStringExtra("keyword"));
        //            resetData();
        //            rl_search_btn();
        //            SPUtil.putBoolean("isKeywordSearch", false);
        //        }else {
        //            getData(true);
        refreshSearchHistory();
        //        }
    }

    @Override
    protected void setListener() {
        auto_tv_search.setOnClickListener(this);
        rl_search_btn.setOnClickListener(this);
        iv_clear_searchrecord.setOnClickListener(this);
        iv_clear_searchtext.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        ll_search_history.setOnClickListener(this);
        multiple_tv_search_record.setOnMultipleTVItemClickListener(onMultClient);
        tipinfo.setOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    tipinfo.setLoading();
                    getSearchData(true);
            }
        });
        search_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        if (ActivityUitl.isNetworkAvailable(ArticleSearchActivity.this) || ArticleSearchListAdapter.getCount() <= 0) {
                            if (data != null && data.getBookFocusData().getBookFocusDataList().size() == 0 && mCurrentPage > 1) {
                                search_foot_view.setVisibility(View.VISIBLE);
                                return;
                            }
                            mModernLoadProgressBar.setShow();
                            if (mIsSearchRequestFinish) {
                                mIsSearchRequestFinish = false;
                                getSearchData(false);
                            }
                        }else {
                            SnackBarNotice.customSnackbarShow(back_layout, R.string.laikan_network_anomaly);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        search_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (mArticleBeanList.size() > 0 && position < mArticleBeanList.size()) {
                    Intent intent = new Intent(mContext, BookFocusDetailActivity.class);
                    intent.putExtra("articleId", mArticleBeanList.get(position).getShorteId());
                    startActivity(intent);
                }
            }
        });
        auto_tv_search.addTextChangedListener(this);
        //        auto_tv_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        //
        //            @Override
        //            public void onFocusChange(View v, boolean hasFocus) {
        //
        //                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
        //                if (!hasFocus) {
        //
        //                    imm.hideSoftInputFromWindow(auto_tv_search.getWindowToken(), 0);
        //                }else {
        //                    imm.hideSoftInputFromWindow(auto_tv_search.getWindowToken(), 0);
        //                }
        //
        //            }
        //        });
        auto_tv_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {

                    // 先隐藏键盘
                    ((InputMethodManager)auto_tv_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ArticleSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    searchArticleData();
                    return true;
                }
                return false;
            }

        });
    }

    @Override
    public void onClick(View v) {
        // 这里可以设定：当搜索成功时，才执行保存操作
        switch (v.getId()) {
            case R.id.ll_search_history:
                hideSoftkeyBoard(v);
                break;
            case R.id.back_layout:
                if (mIsArticleSearchList) {
                    mIsArticleSearchList = false;
                    auto_tv_search.setText("");
                    tipinfo.setHide();
                    search_listview.setVisibility(View.GONE);
                    search_scroll.setVisibility(View.VISIBLE);
                    auto_tv_search.clearFocus();
                }else {
                    finish();
                    if (ArticleSearchActivity.this.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                        ((InputMethodManager)auto_tv_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ArticleSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                        // 隐藏软键盘
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                    }
                    auto_tv_search.clearFocus();
                    //                    setTextEditable(false);
                }
                break;
            case R.id.auto_tv_search:
                //                flag = false;
                auto_tv_search.setCursorVisible(true);
                //                initAutoComplete("article_search_history", auto_tv_search);
                //                auto_tv_search.showDropDown();
                break;
            case R.id.rl_search_btn:
                if (mIsSearchRequestFinish) {
                    mIsSearchRequestFinish = false;
                    searchArticleData();
                }
                break;
            case R.id.iv_clear_searchrecord:
                SPUtil.putString("article_search_history", "");
                refreshSearchHistory();
                break;
            case R.id.iv_clear_searchtext:
                auto_tv_search.setText("");
                searchKeyword = "";
                mIsArticleSearchList = false;
                resetData();
                search_scroll.setVisibility(View.VISIBLE);
                search_listview.setVisibility(View.GONE);
                tipinfo.setHide();
                break;
            default:
                break;
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        if (auto_tv_search.getText() != null && auto_tv_search.getText().length() > 0) {
            iv_clear_searchtext.setVisibility(View.VISIBLE);
        }else {
            iv_clear_searchtext.setVisibility(View.GONE);
        }
    }

    //    private void setTextEditable(boolean isEditable) {
    //        if (isEditable) {
    //            auto_tv_search.setFocusableInTouchMode(true);
    //            auto_tv_search.setFocusable(true);
    //            auto_tv_search.requestFocus();
    //        }else {
    //            auto_tv_search.clearFocus();
    //            auto_tv_search.setFocusable(false);
    //        }
    //    }

    /**
     * 初始化AutoCompleteTextView，最多显示5项提示，使 AutoCompleteTextView在一开始获得焦点时自动提示
     *
     * @param field 保存在sharedPreference中的字段名
     * @param auto 要操作的AutoCompleteTextView
     */
    //    private void initAutoComplete(String field, AutoCompleteTextView auto) {
    //        String longhistory = SPUtil.getString("article_search_history", "");
    //        final String[] hisArrays = longhistory.split(",");
    //        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, hisArrays);
    //        // 只保留最近的50条的记录
    //        if (hisArrays.length > 50) {
    //            String[] newArrays = new String[50];
    //            System.arraycopy(hisArrays, 0, newArrays, 0, 50);
    //            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, newArrays);
    //        }
    //
    //        auto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    //
    //            @Override
    //            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //
    //                searchKeyword = hisArrays[position];
    //                saveHistory("article_search_history", auto_tv_search);
    //                search();
    //                flag = true;
    //            }
    //        });
    //
    //    }

    /**
     * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
     *
     * @param auto_tv_search 要操作的AutoCompleteTextView
     */
    private void saveHistory(AutoCompleteTextView auto_tv_search) {
        String searchKeywrod = auto_tv_search.getText().toString();
        String articleHistory = SPUtil.getString("article_search_history", "");
        if (!articleHistory.contains(searchKeywrod + ",")) {
            StringBuilder sb = new StringBuilder(articleHistory);
            sb.insert(0, searchKeywrod + ",");
            SPUtil.putString("article_search_history", sb.toString());
        }
    }

    private void refreshSearchHistory() {
        multiple_tv_search_record.removeAllViews();
        String searchHistory = SPUtil.getString("article_search_history", "");
        mArticleSearchHistory = searchHistory.split(",");
        if (!TextUtils.isEmpty(searchHistory) && mArticleSearchHistory.length > 0) {
            List<String> searchHistoryList = new ArrayList<String>();
            for (int i = 0; i < mArticleSearchHistory.length; i++) {
                searchHistoryList.add(mArticleSearchHistory[i]);
            }
            multiple_tv_search_record.setOnMultipleTVItemClickListener(onMultClient);
            multiple_tv_search_record.setTextViews(searchHistoryList);
        }
    }

    /**
     * 访问接口获取数据
     */
    private void getSearchData(final boolean isloading) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("pageNo", mCurrentPage + "");
        map.put("queryString", searchKeyword);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                if(isloading){tipinfo.setLoading();}
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                KLog.e("ArticleSearchActivity : " + httpResponse.responseContent);
                // 成功返回时解析json数据
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<ArticleSearchBean>() {}.getType();
                    data = gson.fromJson(httpResponse.responseContent, type);
                    if (data != null) {
                        if (data.getBookFocusData() == null || !Constants.RESULT_OK.equals(data.getResult())) {
                            ToastMgr.showShortToast(data.getError_msg());
                        }else {
                            if(isloading){tipinfo.setHide();}
                            mArticleBeanList.addAll(data.getBookFocusData().getBookFocusDataList());
                            ArticleSearchListAdapter.updateDatas(mArticleBeanList);
                            if (data.getBookFocusData().getBookFocusDataList().size() == 0 && mCurrentPage == 1) {
                                ToastMgr.showShortToast(R.string.request_no_data);
                                search_foot_view.setVisibility(View.GONE);
                            }else if (data.getBookFocusData().getBookFocusDataList().size() == 0 && mCurrentPage > 1) {
                                search_foot_view.setVisibility(View.VISIBLE);
                            }
                            mIsArticleSearchList = true;
                            search_listview.setVisibility(View.VISIBLE);
                            search_scroll.setVisibility(View.GONE);
                            tipinfo.setHide();
                            mCurrentPage++;
                        }
                    }

                }catch (Exception e) {
                    // 数据解析失败
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if(isloading){tipinfo.setLoadError(R.string.laikan_network_anomaly);}
                KLog.e("网络不给力，请重试。57");
            }

            @Override
            public void onFinish() {
                mModernLoadProgressBar.setHide();
                mIsSearchRequestFinish = true;
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_article_search);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    private void resetData() {
        search_foot_view.setVisibility(View.GONE);
        mCurrentPage = 1;
        ArticleSearchListAdapter.clearData();

    }

    private void hideSoftkeyBoard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}